<script setup lang="ts">
import type { FormItemTool } from '../../../types/index.ts'
import { VxeUpload, VxeUploadPropTypes  } from 'vxe-pc-ui'
import type { VxeUploadListeners } from 'vxe-pc-ui'
import {autoUpload} from './http'
import { omit } from 'lodash-es'
type IProps = {
  item: FormItemTool<'upload'>
  allDisabled?: boolean
  isEditByRow?: boolean
  data: Record<string, any>
  formItemRef?: any
}
const emit = defineEmits(['update:data'])
const props = withDefaults(defineProps<IProps>(), {isEditByRow: true,})
const { item, allDisabled, isEditByRow } = toRefs(props)
const value = defineModel<any | any[]>('value')
const elRef = useTemplateRef('elRef')
const getRef = () => {
  return elRef.value
}
const limitCount = computed(() => {
  if(item.value.config?.limitCount) {
    return +item.value.config.limitCount!
  }
  return 1
})
const showUploadButton = computed(() => {
  return item.value.config?.showUploadButton ?? false
})
const uploadParams = computed(() => {
  return item.value.config?.uploadParams ?? {bizType: ''}
})
const valueMode = computed(() => {
  return item.value.config?.valueMode ?? 'id'
})
const fileNameKey = computed(() => {
  if(item.value.config?.mapping === false) return false
  if(item.value.config?.mapping) {
    return item.value.config.mapping['fileName'] ?? 'fileName'
  }
  return 'fileName'
})

onMounted(() => {
  console.log('props.formItemRef',  props.formItemRef);
  
})

const fileName = computed({
  get(): string | undefined {
    if(fileNameKey.value === false) return fileList.value?.map(item => item.name).join(',')
    return Array.isArray(props.data[fileNameKey.value]) ? props.data[fileNameKey.value].join(',') : props.data[fileNameKey.value];
  },
  set(val: string) {
    if(fileNameKey.value === false) return;
    emit('update:data', {...props.data, [fileNameKey.value]: val});
  }
}) as unknown as WritableComputedRef<string | string[] | undefined>;
const fileListOrigin = ref<{id: string;}[]>([])
const fileList = computed({
  get() {
    // 判断是否是数组
    if(Array.isArray(value.value)) {
      if(valueMode.value === 'id') {
        const arr = value.value.slice(0, limitCount.value)
        return arr.map(id => {
          const itemFile = fileListOrigin.value.find(item => item.id === id)
          return {
            id: id,
            name: fileName.value,
            ...(itemFile ?? {})
          }
        })
      }
      return value.value.slice(0, limitCount.value)
    }
    if(value.value) {
      if(valueMode.value === 'id') {
        const itemFile = fileListOrigin.value.find(item => item.id === value.value)
        return [{
          id: value.value,
          name: fileName.value,
          ...(itemFile ?? {})
        }]
      }
      return [value.value]
    }
    return undefined
  },
  set(val: any[]) {
    nextTick(() => {
      nextTick(() => {
        props.formItemRef?.validate?.('change')
      })
    })
    if(limitCount.value === 1) {
      if(valueMode.value === 'id') {
        value.value = val[0]?.id
        fileListOrigin.value = val
      }else {
        value.value = val[0]
        fileListOrigin.value = val[0]
      }
      nextTick(() => { fileName.value = valueMode.value === 'id' ? val[0]?.fileName :val[0]?.name })
      return
    }
    value.value = val.map((item: any) => valueMode.value === 'id' ? item?.id : item)
    nextTick(() => { fileName.value = val.map((item: any) => valueMode.value === 'id' ? item?.fileName : item?.name) }) 
  }
})

const uploadMethod: VxeUploadPropTypes.UploadMethod = (data: any) => {
  if(valueMode.value === 'id') {
    if(item.value.config?.uploadHandle) {
      return item.value.config?.uploadHandle(data.file, uploadParams.value)
    }
    return new Promise((resolve, reject) => {
      autoUpload(data.file, uploadParams.value, data).then((res: any) => {
        const fileMsg = res.data
        const option = data.option
        const arr = [...(fileList.value ?? [])]
        const index = arr.findIndex(item => item['_X_KEY'] === option['_X_KEY'])
        if(index !== -1) {
          arr.splice(index, 1, {
            ...option,
            ...fileMsg
          })
        }else {
          arr.push({
            ...option,
            ...fileMsg
          })
        }
        fileList.value = arr
        resolve({
          name: fileMsg.fileName,
          url: fileMsg.url
        })
      }).catch((_err: Error) => {
        const option = data.option
        const arr = [...(fileList.value ?? [])]
        fileList.value = arr.filter((item: any) => item['_X_KEY'] ===  option['_X_KEY'])
        reject({name: '',url: ''})
      })
    })
  }
  nextTick(() => {
    nextTick(() => {
      nextTick(() => {
        if(fileList.value) {
          fileList.value = fileList.value.map(item => {
            if(item.uid === data.file.uid) item.file = data.file
            return item
          })
        }
      })
    })
  })
  return new Promise(resolve => {
    resolve({
      name: data.file.name,
      url: `${data.file.name}`
    })
  })
}





const add: VxeUploadListeners['add'] =  (_data) => {
  // console.log('add', _data);
  
  // createFormDataFromBlobUrl(_data.option).then(res => {
  //   console.log('file', res);
  // })
  
}  
const selectEvent = () => {
  const $upload = elRef.value
  if ($upload) {
    $upload.choose()
  }
}



defineExpose({
  getRef,
})


</script>
<template>
<span class="w-full bg-white">
  <template v-if="isEditByRow">
    <div class="w-full flex" @click="selectEvent" v-if="!showUploadButton">
      <slot name="corner">
        <el-input placeholder="请选择文件" disabled :value="fileName"></el-input>
        <el-button :disabled="allDisabled || item.config?.disabled" type="primary"> <slot name="uploadText">上传文件</slot> </el-button>
      </slot>
    </div>
    <VxeUpload
      class="w-full"
      :disabled="allDisabled"
      ref="elRef"
      v-model="fileList"
      :drag-to-upload="true"
      show-progress
      show-error-status
      v-bind="omit(item.config, ['uploadHandle', 'uploadParams'])"
      :showUploadButton="showUploadButton"
      :limit-count="limitCount"
      :upload-method="uploadMethod"
      @add="add"
    >
    <div class="w-full flex">
      <slot name="corner">
        <el-input disabled :value="fileList?.map(item => item.name).join(',')"></el-input>
        <el-button type="primary"> <slot name="uploadText">上传文件</slot> </el-button>
      </slot>
    </div>
    </VxeUpload>
  </template>
  <span v-else> {{ fileName }} </span>
</span>
</template>

<style scoped lang="scss"></style>


